package com.ffapp.f9164.td.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
import com.ffapp.f9164.td.R;
import com.ffapp.f9164.td.basis.BasisFragment;
import com.ffapp.f9164.td.basis.Constants;
import com.ffapp.f9164.td.bean.ParamListData;
import com.ffapp.f9164.td.util.CountDown;
import com.ffapp.f9164.td.util.EditTextUtil;
import com.ffapp.f9164.td.util.SoftKeyBoardListener;
import com.ffapp.f9164.td.util.SubstringUtil;
import com.ffapp.f9164.td.view.PopHandle;
import com.suke.widget.SwitchButton;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.BleUtils;
import my.CheckUtils;
import my.LogUtil;

public class CenterFragment extends BasisFragment {

    static CenterFragment fragment;

    public static CenterFragment newInstance() {
        if (fragment == null) {
            fragment = new CenterFragment();
        }
        return fragment;
    }

    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    MyAdapter adapter;
    ArrayList<ParamListData> terminalList;
    ArrayList<ParamListData> originalList;
    public static int SUBMIT = 75;
    private boolean isFinish = false;

    private CountDown mCountDownTimer;
    private static final long MAX_TIME = 11 * 1000;
    private StringBuffer saveResult = new StringBuffer();

    private int subPosition = 0;
    private Handler submitHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 75://75提交
                    isFinish = false;
                    if (subPosition < terminalList.size()) {
                        initSettingSaveThred(subPosition);
                        subPosition++;
                    } else {
                        BleUtils.stopNotify();
                        isFinish = true;
                        originalList.clear();
                        originalList = JSON.parseObject(JSON.toJSONString(terminalList), new TypeReference<ArrayList<ParamListData>>() {
                        }); // Json 转List
                        dismissProgress();
                        mCountDownTimer.cancel();
                        if (!TextUtils.isEmpty(saveResult.toString())) {
                            PopHandle popHandle = new PopHandle(mContext, "tips_fail", "错误信息", saveResult.toString());
                            popHandle.show();
                        } else {
                            showToast("保存成功");
                        }
                    }
                    break;
                case 76:  //检查是否传输完毕
                    try {
                        if (!isFinish && !getActivity().isFinishing()) {
                            showToast("设置失败，请重试");
                            dismissProgress();
                            BleUtils.stopNotify();
                        }
                    } catch (NullPointerException e) {
                        throw e;
                    }
                    break;
            }

        }
    };

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            LogUtil.d("终端fragment显示");
        } else {
            //相当于OnPause()
            LogUtil.d("终端fragment隐藏");
        }
    }

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.fragment_terminal);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
        initCountDownTimer();
    }

    public void initCountDownTimer() {
        mCountDownTimer = new CountDown();
        mCountDownTimer.setMillisInFuture(MAX_TIME);
        mCountDownTimer.setCountdownInterval(1000);
        mCountDownTimer.setCountDownListener(new CountDown.CountDownListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {
                submitHandler.sendEmptyMessage(Constants.CHECK_FINISH);
                //这时候可以做30秒的计时操作
            }

            @Override
            public void onTick(long millisUntilFinished) {
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        terminalList = new ArrayList<>();
        originalList = new ArrayList<>();
    }

    String[] serverPsws;
    String[] serverPswsTwo;


    public void setList(String sMsgObjString, int type) {
        terminalList.clear();
        if (!TextUtils.isEmpty(sMsgObjString)) {

            //服务器数量
            String serversNum = SubstringUtil.subString(sMsgObjString, "Total Servers:");
            terminalList.add(new ParamListData("中心服务器个数", 2, "" + serversNum, "AT+SVRCNT", "(1-2)", true));


            //服务器
            List<String> serverList = Arrays.asList(getResources().getStringArray(R.array.server));
            terminalList.add(new ParamListData("服务器", 1, "" + serverList.get(Integer.valueOf(serversNum) - 1), serverList, "AT+SVRPARM", false));


            //服务器通道1
            String serverPsw = SubstringUtil.subString(sMsgObjString, "Server Para1:");
            serverPsws = serverPsw.split(",");
            List<String> serverPswList = Arrays.asList(getResources().getStringArray(R.array.serverPsw));
            terminalList.add(new ParamListData("服务器通道", 1, "" + serverPsws[0], serverPswList, "AT+SVRPARM", false));

            //服务器通道2
            String serverPswTwo = SubstringUtil.subString(sMsgObjString, "Server Para2:");
            if (TextUtils.isEmpty(serverPswTwo)) {
                serverPswsTwo = new String[]{"无", ""};
            } else {
                serverPswsTwo = serverPswTwo.split(",");
            }


            //服务器地址
            terminalList.add(new ParamListData("服务器地址", 2, "" + serverPsws[1], "AT+SVRPARM", "", true));

            //首选DNS服务器
            String dns1 = SubstringUtil.subString(sMsgObjString, "Dns1:");
            terminalList.add(new ParamListData("首选DNS服务器", 2, "" + dns1, "AT+DNS", "", true));

            //备份DNS服务器
            String dns2 = SubstringUtil.subString(sMsgObjString, "Dns2:");
            terminalList.add(new ParamListData("备份DNS服务器", 2, "" + dns2, "AT+BKDNS", "", true));

            //APN
            String apn = SubstringUtil.subString(sMsgObjString, "APN:");
            terminalList.add(new ParamListData("APN", 2, "" + apn, "AT+APN", "", true));

            //APN拨号号码
            String dialNo = SubstringUtil.subString(sMsgObjString, "Dial No.:");
            terminalList.add(new ParamListData("APN拨号号码", 2, "" + dialNo, "AT+CENT", "", true));

            //APN用户名
            String userName = SubstringUtil.subString(sMsgObjString, "User Name:");
            terminalList.add(new ParamListData("APN用户名", 2, "" + userName, "AT+DNAME", "", true));

            //APN密码
            String userPwd = SubstringUtil.subString(sMsgObjString, "User Pwd:");
            terminalList.add(new ParamListData("APN密码", 2, "" + userPwd, "AT+DPWD", "", true));

            //蓝牙名称
            String blueName = SubstringUtil.subString(sMsgObjString, "Bluetooth Name:");
            terminalList.add(new ParamListData("蓝牙名称", 2, "" + blueName, "AT+BHTNAME", "", false));

            //蓝牙密码
            String bluePwd = SubstringUtil.subString(sMsgObjString, "Bluetooth Pwd:");
            terminalList.add(new ParamListData("APN密码", 2, "" + bluePwd, "AT+BHTPWD", "", true));


            if (type == Constants.AT_FROM_DEVICE) {
//                ArrayList<ParamListData> n = (ArrayList<ParamListData>) JSON.parseArray(a,ParamListData.class); // Json 转List
                originalList = JSON.parseObject(JSON.toJSONString(terminalList), new TypeReference<ArrayList<ParamListData>>() {
                }); // Json 转List
            }
        }

        adapter.notifyDataSetChanged();
        recyclerView.setAdapter(adapter);
    }

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

        public MyAdapter() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_terminal_item, viewGroup, false);
            return new ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.list_item.setTag(position);
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return terminalList == null ? 0 : terminalList.size();
        }


        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.list_item)
            LinearLayout list_item;
            @BindView(R.id.tv_name)
            TextView tvName;
            @BindView(R.id.edit_text)
            EditText editText;
            @BindView(R.id.img_spanner)
            ImageView imgSpanner;
            @BindView(R.id.tv_unit)
            TextView tvUnit;
            @BindView(R.id.tv_synchro)
            TextView tvSynchro;
            @BindView(R.id.switch_btn)
            SwitchButton switchBtn;

            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
                EditTextUtil.setEditTextNoEmoji(editText);
            }

            public void bind(int position) {
                ParamListData terminalListData = terminalList.get(position);
                tvName.setText(terminalListData.getName());
                switch (terminalListData.getType()) {
                    case 1: //spinner
                        editText.setText("" + (TextUtils.isEmpty(terminalListData.getValue()) ? terminalListData.getKey() : terminalListData.getValue()));
                        editText.setHint("请选择" + terminalListData.getName());
                        editText.setEnabled(terminalListData.isEnable());
                        imgSpanner.setVisibility(View.VISIBLE);
                        tvUnit.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        tvSynchro.setVisibility(View.GONE);
                        list_item.setBackgroundResource(R.color.white);
                        break;
                    case 2:  // edit
                        editText.setText("" + terminalListData.getValue());
                        editText.setHint("请输入" + terminalListData.getName());
                        editText.setEnabled(terminalListData.isEnable());
                        editText.setVisibility(View.VISIBLE);
                        tvUnit.setVisibility(View.VISIBLE);
                        tvUnit.setText(terminalListData.getUnit());
                        imgSpanner.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        tvSynchro.setVisibility(View.GONE);

                        list_item.setBackgroundResource(R.color.white);
                        break;
                }
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        int curPosition = getAdapterPosition();
                        ParamListData data = terminalList.get(curPosition);
                        data.setValue(s.toString());
                        if (s.toString().equals("移动OneNET")) {
                            terminalList.get(3).setValue("183.230.40.39:5683");
                            adapter.notifyItemChanged(3);
                        }
                    }
                });

                imgSpanner.setTag(terminalListData);
                tvSynchro.setTag(terminalListData);
            }

            @OnClick(R.id.img_spanner)
            public void showSpanner(View v) {
                SoftKeyBoardListener.hideKeyboard(getActivity());
                final ParamListData terminalListData = (ParamListData) v.getTag();
                OptionsPickerView pickerView = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        String text = terminalListData.getValues().get(options1);
                        switch (text) {
                            case "服务器1":
                                terminalList.get(2).setKey(serverPsws[0]);
                                terminalList.get(3).setValue(serverPsws[1]);
                                adapter.notifyItemChanged(2);
                                adapter.notifyItemChanged(3);
                                break;
                            case "服务器2":
                                terminalList.get(2).setKey(serverPswsTwo[0]);
                                terminalList.get(3).setValue(serverPswsTwo[1]);
                                adapter.notifyItemChanged(2);
                                adapter.notifyItemChanged(3);
                                break;
                        }
                        editText.setText(text);
                    }
                })
                        .setSubmitText("确定")//确定按钮文字
                        .setCancelText("取消")//取消按钮文字
                        .build();
                pickerView.setPicker(terminalListData.getValues());
                pickerView.show();
            }
        }
    }


    @OnClick(R.id.btn_save)
    public void save() {
        final StringBuffer atShowResult = new StringBuffer();

        BleUtils.notify(new BleNotifyCallback() {
            @Override
            public void onNotifySuccess() {

            }

            @Override
            public void onNotifyFailure(BleException exception) {
                BleLog.d("下发设置打开通知操作失败");
            }

            @Override
            public void onCharacteristicChanged(byte[] data) {
                for (Byte a : data) {
                    atShowResult.append(String.format("%02X", a));
                }
                String sMes = HexUtil.hexStringToString(atShowResult.toString());
                if (sMes.contains("OK")) {
                    originalList.set(subPosition - 1, terminalList.get(subPosition - 1));
                    atShowResult.setLength(0);
                    submitHandler.sendEmptyMessage(Constants.SUBMIT);
                }else if(sMes.contains("ERROR")){
                    atShowResult.setLength(0);
                    onError();
                }
            }

            @Override
            public void onError() {
                saveResult.append(terminalList.get(subPosition - 1).getName() + "保存失败" + "\r\n");
                submitHandler.sendEmptyMessage(Constants.SUBMIT);
            }
        });

        showLoading();
        saveResult.setLength(0);
        subPosition = 0;
        submitHandler.sendEmptyMessage(Constants.SUBMIT);
    }

    public void initSettingSaveThred(final int position) {
        String url = getBlueToothUrl(terminalList.get(position), 1);
        if (TextUtils.isEmpty(url) && terminalList.get(position).getName().equals("首选DNS服务器") || TextUtils.isEmpty(url) && terminalList.get(position).getName().equals("备份DNS服务器")) {
            showToast(terminalList.get(position).getName()+"的值不能为空");
            dismissProgress();
//            submitHandler.sendEmptyMessage(Constants.SUBMIT);
            return;
        }
        String originalurl = getBlueToothUrl(originalList.get(position), 0);
        if (originalurl.equals(url)) {
            submitHandler.sendEmptyMessage(Constants.SUBMIT);
            return;
        }

        final String toSet = url;
        BleUtils.write(toSet, new BleWriteCallback() {
            @Override
            public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                if (current == total) {
                    mCountDownTimer.start();
                }
            }

            @Override
            public void onWriteFailure(final BleException exception) {
                saveResult.append(terminalList.get(position).getName() + "保存失败" + "\r\n");
            }
        });


    }

    private String serverNum;
    private String serverType;
    private String serverIp;

    /**
     * @param data
     * @param type 0 = 原始数据    1=修改后的数据
     * @return
     */
    private String getBlueToothUrl(ParamListData data, int type) {

        String url;
        String name = data.getName();
        String at = data.getAction();
        String value = (data.getValue() == null) ? data.getKey() : data.getValue();
//        if (TextUtils.isEmpty(value) || "数据异常，请重新获取".equals(value)) {
////            return null;
//            return "";
//        }

        switch (name) {
            case "服务器":
                switch (value) {
                    case "服务器1":
                        serverNum = "1";
                        break;
                    case "服务器2":
                        serverNum = "2";
                        break;
                }
                return "";
            case "服务器通道":
                switch (value) {
                    case "无":
                        serverType = "0";
                        break;
                    case "TCP":
                        serverType = "1";
                        break;
                    case "UDP":
                        serverType = "2";
                        break;
                    case "串口":
                        serverType = "3";
                        break;
                    case "电信IoT/华为OC":
                        serverType = "4";
                        break;
                    case "LoRa":
                        serverType = "5";
                        break;
                    case "移动OneNET":
                        serverType = "6";
                        return "";
                }
                return "";
            case "服务器地址":
                if(type == 1){
                    value = serverNum + "," + serverType + "," + value;
                }
                break;
        }

        String a = null;
        try {
            a = HexUtil.chineseWordToGbk((at + "=" + value)) + "0D0A";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return url = a;
    }
}
